import { useEffect ,useRef , useCallback} from 'react'
import { Progress, DatePicker, Tooltip, message } from 'antd'
import { TrophyOutlined  } from '@ant-design/icons'
import { usePageTitle } from '@/hooks'
import dayjs, { Dayjs } from 'dayjs'
import { pageGoal } from '@/service/goal'
import { listReview } from '@/service/review'
import { useRequest } from 'ahooks'
import MarkDown from '@/components/markdown'
import { useNavigate } from 'react-router-dom'
import { useMobile } from '@/hooks'
import * as echarts from 'echarts/core';
import { TitleComponent, CalendarComponent, TooltipComponent,VisualMapComponent } from 'echarts/components';
import { HeatmapChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import type { EChartsOption } from 'echarts'
import "./index.less"

echarts.use([
  TitleComponent,
  CalendarComponent,
  TooltipComponent,
  VisualMapComponent,
  HeatmapChart,
  CanvasRenderer
]);


const thisYear =  dayjs(`${new Date().getFullYear()}` , "YYYY") 

const Nav = ({title , extra}:{title:string , extra?:JSX.Element})=>{
  return (
    <nav className='nav'>
      <div className='title'> {title} </div>
      <div className='select'>
        { extra }
      </div>
    </nav>
  )
}

const option:EChartsOption = {
  title: {
    top: 240,
    left: 40,
    text: '成就值算法：目标*0.5 + 状态*0.3 + 日记*0.1 + 心流*0.1'
  },
  legend: { show: true },
  tooltip: {
    formatter: (params:any) => {
      const { value } = params;
      const [date, status] = value
      return (
        `<div>
          <div>日期：${date}</div>
          ${ status === 0 ? "暂无记录": `<div>成就值：${status}</div>`}
        <div>`
      )
    }
  },
  visualMap: {
    show:false,
    min: 0,
    max: 100,
    inRange: {
      color:["#fff" , "#0066ff"]
    },
  },
  calendar: {
    range: '2023',
    left: 60,
    top: 60,
  },
  series: {
    type: 'heatmap',
    coordinateSystem: 'calendar',
    data: []
  }
}

export default function Goal() {

  usePageTitle("目标")

  const navigate = useNavigate()

  const { data:goalList = [] , run: loadGoal } = useRequest(async (year:number = new Date().getFullYear()) => {
    const { records } = await pageGoal({ current: 1, pageSize: 100 ,year });
    return records || []
  })

  const echartRef = useRef<HTMLDivElement>(null);
  const calendarInstance = useRef<echarts.ECharts>();

  const { data: reviewList } = useRequest(listReview)
  
  const { isMobile } = useMobile()

  const onDateChange = (_: Dayjs | null, dateString: string) => {
    loadGoal(Number(dateString))
  }

  const getVirtualData = useCallback((year:string , reviewMap:Record<string , App.ReviewItem>)=> {
    const date = +echarts.time.parse(year + '-01-01');
    const end = +echarts.time.parse(year + '-12-31');
    const dayTime = 3600 * 24 * 1000;
    const data = [];

    const getAchievement = (status:number , goal:number , note:number , heart:number ) => {
      return status*0.3 + goal*0.5 + note*0.1 + heart*0.1
    }

    for (let time = date; time <= end; time += dayTime) {
      const day = echarts.time.format(time, '{yyyy}-{MM}-{dd}', false)
      // 先写死一个成就值算法
      const currentReview = reviewMap[day]

      if (currentReview) {

        const { review_status = 50, goals = '', remark = '' , heart } = currentReview

        const goal = (goals.split(",").length || 0) * 35

        const mark = remark.length * 0.5;

        const heart_ = heart ? 100 : 0;

        const value = getAchievement(review_status , goal , mark , heart_ )

        data.push([day, value]);
        
      } else {

        data.push([ day , 0 ]);
      }
    }
    return data;
  },[])

  useEffect(() => {
    !isMobile && echartInit()
  }, [])

  const renderCalendar = (reviewList: App.ReviewItem[]) => {
    
    if (calendarInstance.current) {

      const reviewMap: Record<string, App.ReviewItem> = {};

      reviewList.forEach(review => {
        const date = dayjs(review.review_date).format("YYYY-MM-DD")
        reviewMap[date] = review
      })

      const yearData = getVirtualData(thisYear.format(`${new Date().getFullYear()}`), reviewMap);
      
      calendarInstance.current.on("click", ({ value }) => {
        const [day] = value as any[];
        const { id } = reviewMap[day];
        navigate(`/review/${id}`)
      })

      calendarInstance.current.setOption({
        series: [
          {
            data: yearData
          }
        ]
      })
    }

  }

  const echartInit = () => {
    if (!echartRef.current) return;
    calendarInstance.current = echarts.init(echartRef.current);
    calendarInstance.current?.setOption(option);
  }

  useEffect(() => {
    if (reviewList && !isMobile) {
      setTimeout(() => {
      echartInit()
      renderCalendar(reviewList)
      },1000)
    }
  }, [isMobile])
  
  useEffect(() => {
    if (reviewList) {
      renderCalendar(reviewList)
    }
  } , [reviewList])

  return (
    <div className="goal">
      <Nav 
        title='年度目标' 
        extra={
          <DatePicker 
            picker='year'
            disabledDate={(date)=> Number(date.format("YYYY")) <= 2022}
            defaultValue={thisYear}
            size="small"
            onChange={onDateChange}
          />
        }
      />
      <div className='goal-content'>
        {
          goalList.map(goal => {
            const { all_num, finish_num } = goal
            const safeNum = (finish_num / all_num)*100
            const percent = safeNum.toFixed(1)
            return (
              <div className='goal-item-year' key={goal.id}>
                <Progress 
                  type='dashboard'
                  percent={ safeNum }
                  format={() => {
                    return (
                      <Tooltip title={ `${finish_num}/${all_num}`}>
                        { percent }%
                      </Tooltip>
                    )
                  }}
                  showInfo
                  width={240}
                />
                <Tooltip>
                  <div
                    className='desc'
                    onClick={() => {
                      const target = document.querySelector(`#anchor-${goal.id}`);
                      const app = document.querySelector(".App")
                      if (target && app) {
                        const top = (target as HTMLDivElement).offsetTop;
                        app.scrollTop = top - 60
                      }
                    }}
                  >
                    {goal.title}
                  </div>
                </Tooltip>
              </div>
            )
          })
        }
      </div>
      {
        !isMobile ? (
          <>
            <Nav title='年度日历' />
            <div className='calendar'>
              <div className='goal-calendar' ref={echartRef}/>
            </div>
          </>
        ) : null
      }
      <Nav title='目标文档' />
      <div className='goal-description'>
        {
          goalList.map(goal => {
            return (
              <div className='desc-item' key={goal.id} id={`anchor-${goal.id}`}>
                <div className="item-title">
                  <TrophyOutlined className="prize"/>
                  <span className="font">{goal.title}</span>
                </div>
                <MarkDown children={goal.content || ""} style={{marginTop:20}}/>
              </div>
            )
          })
        }
      </div>
    </div>
  )
}